<?php

namespace App\Http\Service;

use App\Libs\HttpCurlLibrary;
use Illuminate\Support\Facades\Config;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\DB;
use App\Http\Service\PostaiService;
use App\Http\Service\Brand\CategorymappingService;
use App\Http\Service\Brand\BrandmappingService;
//里边是python的转链接口
class PythonService extends BaseService
{
   
    public function __construct(PostaiService $postaiService,CategorymappingService $categorymappingService,BrandmappingService $brandmappingService)
    {
        parent::__construct();
        $this->URL_MAP=config('myurl.URL_MAP');
        $this->postaiService=$postaiService;
        $this->categorymappingService=$categorymappingService;
        $this->brandmappingService=$brandmappingService;
    }

    #值得买-解析
    public  function SmzdmLianJieJieXi($request,$data=[],$is_zdm=true)
    {
        if($is_zdm){
            $url="http://test-node.lottefuture.com/smzdm/";
            $shop_buy_url=removeProtocol($data['shop_buy_url']);
            $params=[
                'url'=>"https://{$shop_buy_url}"
            ];
            $data=json_get($url, $params);
            //dd($data);
            if($data['status']==200){
                if(isset($data['data'])){
                    $restoredLink=$data['data']['restoredLink'];
                   // dd($restoredLink);

                }else{
                    //die("SAdfsa");
                    $restoredLink="https://{$shop_buy_url}";
                }

            }else{
                $restoredLink="https://{$shop_buy_url}";
            }
        }else{
            $restoredLink=$data['shop_buy_url'];
        }

       // die("666");
        $url2="http://cgi-bin.lottefuture.com/python/link-batch-parse.php";
        $postdata =[
            "content"=>$restoredLink
        ];


        $headers = [
            'Content-Type: application/json; charset=utf-8',
        ];

        //dd($postdata);
        $data2=json_post($url2, $postdata, $headers);
        //dd($data2);
        //dd($data2['data']);
        $items=$data2['data']['items'];
        //dd($items);
        $result=[];
        $result2=[];
        $msg1="成功";
        $msg2="";
        $msg3="";
        foreach($items as $v){

            $data5=[];
            $matchedText=$v['matchedText'];

            $success=$v['success'];

            if($success){
                $matchedPlatforms=$v['matchedPlatforms'];
                //dd($matchedPlatforms);
                foreach($matchedPlatforms as $v1){

                    if(!isset($v1['result'])){
                        continue;
                    }
                    
                    ///dd($matchedText);
                    $type=$v1['result']['type'];
                    //echo $type;
                    //type =3活动 1商品  6 其他
                    if($type=='1'){
                        $productInfo=$v1['result']['productInfo'];
                        //dd($productInfo);
                        $data5=[
                            'platform'=>$productInfo['platformName'],
                            'product_id'=>$productInfo['productId'],
                            'matchedText'=>$matchedText,
                            'product_msg_all'=>$items
                        ];
                        $result[]=$data5;
                    }

                    //其他
                    if($type=='6'){
                        $productInfo=$v1['result']['otherInfo'];
                        //dd($productInfo);
                        $data6=[
                            'platform'=>$productInfo['platformName'],
                            'product_id'=>'',
                            'matchedText'=>$matchedText,
                            'product_msg_all'=>$items
                        ];
                        $result2[]=$data6;
                        $msg3="非商品";
                    }




                    
                }
                
            }else{
                $platformName_msg="";
                $errorMessage_msg="";
                $matchedPlatforms=$v['matchedPlatforms'];
                foreach ($matchedPlatforms as $k2=>$v2){
                    if(isset($v2['platformName'])){
                        $platformName_msg=$v2['platformName'];

                    }
                    if(isset($v2['errorMessage'])){
                        $errorMessage_msg=$v2['errorMessage'];
                    }
                    if(!empty($platformName_msg)){
                        $msg2.="{$platformName_msg}";
                    }

                    if(!empty($errorMessage_msg)){
                        $msg2.="{$errorMessage_msg}";
                    }
                    
                   
                }
            }
           
       }
       //dd($result);
        if(count($result)<1){
            $result=$result2;
            
        }
        if(count($result)<1){
            $postdata_json=json_encode($postdata);
            $msg=json_encode($data2);
            $msg1="【转链失败，商品不支持推广或未完成平台授权】";
            $resultdata=[
                'code'=>'0',
                'msg'=>"{$msg1}{$msg2}{$msg3}",
                'result'=>$result
            ];
            return $resultdata;
            //$this->error("{$msg1}{$msg2}{$msg3}");
            //$this->error("不能解析  接口   http://cgi-bin.lottefuture.com/python/link-parse.php   方式post  参数  {$restoredLink}   返回结果 {$msg}  ");
        }
        #判断产品id是否为空
        /*if(empty($result['product_id'])){
            $this->error("{$msg1}{$msg2}原因【{$msg3}】");
        }*/

       // dd($result);
        $resultdata=[
            'code'=>'1',
            'msg'=>"{$msg1}{$msg2}{$msg3}",
            'result'=>$result
        ];
        return $resultdata;
       
    }
    #自用其他平台调用接口
    public function  get_other_platform($product_id,$platform_name)
    {
        $getinfo_url="http://xdrj.lottefuture.com/xf-cgi/goods/detail";
        $user_params=[
            "product_id"=>$product_id,
            "platform"=> $platform_name,
            "user_id"=> 1006

        ];
        //dd($user_params);
        $result=[
                "brand_name"=>'', 
                "title"=>'', 
                "category_name"=>'', 
                "commission_rate"=>0.00, 
                "subsidy_rate"=>0.00,
                "total_commission_rate"=>0.00, 
                "income_rate"=>0.00, 
                "commission_amount"=>0.00, 
                "is_owner"=>false,
                "productImage"=>[], 
                "productId"=>'', 
                "item_id"=>'', 
                "productName"=>'',
                "productUrl"=>'',
                'platform_name'=>$platform_name,
                'standard_category_name'=>'',
                'standard_brand_name'=>'',
                'original_category_name'=>'',
                'original_brand_name'=>'',
            ];
        
        $userai_data=[];
        $postdata=json_post($getinfo_url,$user_params);
        if(isset($postdata['status'])&&$postdata['status']='200'){
            $user_data=$postdata['data'];
            //dd($user_data);
            $commission_rate=0.00;
            if(isset($user_data['commission_rate'])){
                $commission_rate=$user_data['commission_rate'];
            }
            $title="";
            if(isset($user_data['name'])){
                $title=$user_data['name'];
            }
            $subsidy_rate=0.00;
            $is_subsidy_post = 0;
            if(isset($user_data['platform_subsidy'])){
                
                $platform_subsidy=$user_data['platform_subsidy'];
                if(isset($platform_subsidy[0])){
                    $platform_subsidy=$platform_subsidy[0];
                    //dd($platform_subsidy['subsidy_rate']);
                    if(isset($platform_subsidy['subsidy_rate'])){
                       // dd($platform_subsidy);
                        $subsidy_rate=$platform_subsidy['subsidy_rate'];

                    }
                    if(isset($platform_subsidy['subsidy_amount'])){
                        $subsidy_amount_post=$platform_subsidy['subsidy_amount'];
                    }

                    if(isset($platform_subsidy['subsidy_name'])){
                        $subsidy_name_post=$platform_subsidy['subsidy_name'];
                    }

                }
                
                ///dd($subsidy_amount);

            }


            $productName="";
            if(isset($user_data['name'])){
                $productName=$user_data['name'];
            }
            $standard_category_name="";
            if(isset($user_data['standard_category'])){
                $standard_category_name=$user_data['standard_category'];
            }
            $original_category_name="";
            if(isset($user_data['original_category'])){
                $original_category_name=$user_data['original_category'];
            }
            $standard_brand_name="";
            if(isset($user_data['standard_brand'])){
                $standard_brand_name=$user_data['standard_brand'];
            }
            $original_brand_name="";
            if(isset($user_data['original_brand'])){
                $original_brand_name=$user_data['original_brand'];
            }
            $productImage=[];
            if(isset($user_data['img'])){
                $productImage[]=$user_data['img'];
            }
            $result=[
                "brand_name"=>$standard_brand_name, 
                "title"=>$title, 
                "category_name"=>$standard_category_name, 
                "commission_rate"=>$commission_rate, 
                "subsidy_rate"=>$subsidy_rate,
                "total_commission_rate"=>0.00, 
                "income_rate"=>0.00, 
                "commission_amount"=>$commission_rate, 
                "is_owner"=>false,
                "productImage"=>$productImage, 
                "productId"=>$product_id, 
                "item_id"=>$product_id, 
                "productName"=>$productName,
                "productUrl"=>'',
                'platform_name'=>$platform_name,
                'standard_category_name'=>$standard_category_name,
                'standard_brand_name'=>$standard_brand_name,
                'original_category_name'=>$original_category_name,
                'original_brand_name'=>$original_brand_name,
            ];

           // dd($user_data);
        }
        //dd($result);
        return $result;
    }

    #其他平台调用ai接口
    public function  get_other_platform33($product_id,$platform_name)
    {
        $getinfo_url="http://xdrj.lottefuture.com/zxy/V1/Gen2/ed1XF/ItemsController/ItemsManage/getInfo";
        $user_params=[
            "product_id"=>$product_id,
            "platform"=> $platform_name,
            "user_id"=> 1006

        ];
        $result=[
                "brand_name"=>'', 
                "title"=>'', 
                "category_name"=>'', 
                "commission_rate"=>0.00, 
                "subsidy_rate"=>0.00,
                "total_commission_rate"=>0.00, 
                "income_rate"=>0.00, 
                "commission_amount"=>0.00, 
                "is_owner"=>false,
                "productImage"=>[], 
                "productId"=>'', 
                "item_id"=>'', 
                "productName"=>'',
                "productUrl"=>'',
                'platform_name'=>$platform_name,
                'standard_category_name'=>'',
                'standard_brand_name'=>'',
                'original_category_name'=>'',
                'original_brand_name'=>'',
            ];
        
        $userai_data=[];
        $postdata=json_post($getinfo_url,$user_params);
        if(isset($postdata['status'])&&$postdata['status']='200'){
            $user_data=$postdata['data'];
            //dd($user_data);
            $commission_rate=0.00;
            if(isset($user_data['commission_rate'])){
                $commission_rate=$user_data['commission_rate'];
            }
            $title="";
            if(isset($user_data['name'])){
                $title=$user_data['name'];
            }
            $subsidy_rate=0.00;
            $is_subsidy_post = 0;
            if(isset($user_data['platform_subsidy'])){
                
                $platform_subsidy=$user_data['platform_subsidy'];
                if(isset($platform_subsidy[0])){
                    $platform_subsidy=$platform_subsidy[0];
                    //dd($platform_subsidy['subsidy_rate']);
                    if(isset($platform_subsidy['subsidy_rate'])){
                       // dd($platform_subsidy);
                        $subsidy_rate=$platform_subsidy['subsidy_rate'];

                    }
                    if(isset($platform_subsidy['subsidy_amount'])){
                        $subsidy_amount_post=$platform_subsidy['subsidy_amount'];
                    }

                    if(isset($platform_subsidy['subsidy_name'])){
                        $subsidy_name_post=$platform_subsidy['subsidy_name'];
                    }

                }
                
                ///dd($subsidy_amount);

            }


            $productName="";
            if(isset($user_data['name'])){
                $productName=$user_data['name'];
            }
            $standard_category_name="";
            if(isset($user_data['standard_category'])){
                $standard_category_name=$user_data['standard_category'];
            }
            $original_category_name="";
            if(isset($user_data['original_category'])){
                $original_category_name=$user_data['original_category'];
            }
            $standard_brand_name="";
            if(isset($user_data['standard_brand'])){
                $standard_brand_name=$user_data['standard_brand'];
            }
            $original_brand_name="";
            if(isset($user_data['original_brand'])){
                $original_brand_name=$user_data['original_brand'];
            }
            $productImage=[];
            if(isset($user_data['img'])){
                $productImage[]=$user_data['img'];
            }
            $result=[
                "brand_name"=>$standard_brand_name, 
                "title"=>$title, 
                "category_name"=>$standard_category_name, 
                "commission_rate"=>$commission_rate, 
                "subsidy_rate"=>$subsidy_rate,
                "total_commission_rate"=>0.00, 
                "income_rate"=>0.00, 
                "commission_amount"=>$commission_rate, 
                "is_owner"=>false,
                "productImage"=>$productImage, 
                "productId"=>$product_id, 
                "item_id"=>$product_id, 
                "productName"=>$productName,
                "productUrl"=>'',
                'platform_name'=>$platform_name,
                'standard_category_name'=>$standard_category_name,
                'standard_brand_name'=>$standard_brand_name,
                'original_category_name'=>$original_category_name,
                'original_brand_name'=>$original_brand_name,
            ];

           // dd($user_data);
        }
        return $result;
    }
    #值得买获取产品id
    public function  getMoneyRate($request,$data)
    {
       // die("SAdfa");
        #判断产品id是否为空
        if(empty($data['product_id']))
        {
            $BUY_PLATFORM=$data['platform_name'];
            #获取真正的平台
            $platform_name=get_platform($BUY_PLATFORM);
            //dd($productName);
            $result=[
                "brand_name"=>'', 
                "title"=>'', 
                "category_name"=>'', 
                "commission_rate"=>0.00, 
                "subsidy_rate"=>0.00,
                "total_commission_rate"=>0.00, 
                "income_rate"=>0.00, 
                "commission_amount"=>0.00, 
                "is_owner"=>false,
                "productImage"=>[], 
                "productId"=>'', 
                "item_id"=>'', 
                "productName"=>'',
                "productUrl"=>'',
                'platform_name'=>$platform_name,
                'standard_category_name'=>'',
                'standard_brand_name'=>'',
                'original_category_name'=>'',
                'original_brand_name'=>'',
            ];
            return $result;
        }
        $URL_MAP=$this->URL_MAP;

        $platform_name=$data['platform_name'];
        if(isset($URL_MAP[$platform_name])){
            $url=$URL_MAP[$platform_name];
            #其他平台
            if(empty($url)){
                $get_other_platform=$this->get_other_platform($data['product_id'],$platform_name);
                return $get_other_platform;
            }
            $params=[
                'itemId'=>$data['product_id']
            ];
            //dd($params);
                // 构建完整的 URL
            $url = $url . '?' . http_build_query($params);
            //dd($url);
            $ch = curl_init();
            curl_setopt_array($ch, [
                CURLOPT_URL => $url,
                CURLOPT_RETURNTRANSFER => true,
                CURLOPT_TIMEOUT => 5,
                CURLOPT_SSL_VERIFYPEER => false,
                CURLOPT_SSL_VERIFYHOST => false,
                CURLOPT_HTTPHEADER => ['Connection: Close'],
                CURLOPT_FOLLOWLOCATION => true
            ]);
            
            $response = curl_exec($ch);
            $httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
            curl_close($ch);

            if ($httpCode === 200 && $response) {
                $platformData= json_decode($response, true);
                
                //dd($platformData);
                $json=extract_title_img_name_url($platformData, $platform_name);
               // dd($json);
                $result_2=calculateMoneyCount($platformData, $platform_name);
                //dd($json);
                $result=[];
                $result=array_merge($json,$result_2);
                $result['platform_name']=$platform_name;

                #重新赋值
                $result['productId']=$data['product_id'];
                $result['platform_name']=$data['platform_name'];

                #获取分类名称
                $category_name=$result['original_category_name'];
                if(!empty($category_name)){
                    $standard_category_name=$this->categorymappingService->targetCategory($category_name);
                }else{
                    $standard_category_name='未知';
                }
                

                #获取品牌名称
                $brand_name=$result['original_brand_name'];
                if(!empty($brand_name)){
                    $standard_brand_name=$this->brandmappingService->targetBrand($brand_name);
                }else{
                    $standard_brand_name="未知";
                }
                
                $result['standard_category_name']=$standard_category_name;
                $result['standard_brand_name']=$standard_brand_name;
                //dd($result);
                return $result;
            } 

        }else{
            
            return [
                "brand_name"=>'', 
                "title"=>'', 
                "category_name"=>'', 
                "commission_rate"=>0.00, 
                "subsidy_rate"=>0.00,
                "total_commission_rate"=>0.00, 
                "income_rate"=>0.00, 
                "commission_amount"=>0.00, 
                "is_owner"=>false,
                "productImage"=>[], 
                "productId"=>'', 
                "item_id"=>'', 
                "productName"=>'',
                "productUrl"=>'',
                'platform_name'=>$platform_name,
                'standard_category_name'=>'',
                'standard_brand_name'=>'',
                'original_category_name'=>'',
                'original_brand_name'=>'',
            ];
        }
        
    }

    public function categoryBrand($request,$data)
    {

        #获取分类名称
        $category_name=$data['original_category_name'];
        $category_name=cleanTextThoroughly($category_name);
        //dd($category_name);

        $standard_category_name=$this->categorymappingService->targetCategory($category_name);

        #获取品牌名称
        $brand_name=$data['original_brand_name'];
        $brand_name=cleanTextThoroughly($brand_name);
        $standard_brand_name=$this->brandmappingService->targetBrand($brand_name);
        
        $result=[
            'standard_category_name'=>$standard_category_name,
            'standard_brand_name'=>$standard_brand_name,
        ];
        return $result;
    }

    // 检测字符串是否包含特定关键词
    public function containsKeyword($string, $keyword) {
        return strpos($string, $keyword) !== false;
    }


    //获取商品详情
    public function get_goods_detail($request,$data)
    {
        $platform_name=$data['platform_name'];
        $product_id=$data['product_id'];
        if($this->containsKeyword($platform_name,'淘宝') ){
            $url="http://cgi-bin.lottefuture.com/python/taobao-goods-query.php";
            $platform_name="淘宝";
        }else if($this->containsKeyword($platform_name,'京东')){
            $url="http://cgi-bin.lottefuture.com/python/jd-goods-query.php";
            $platform_name="京东";
        }else if($this->containsKeyword($platform_name,'拼多多')){
            $url="http://cgi-bin.lottefuture.com/python/pdd-goods-query.php";
            $platform_name="拼多多";
        }else if($this->containsKeyword($platform_name,'唯品会')){
            $url="http://cgi-bin.lottefuture.com/python/vipshop-goods-query.php";
            $platform_name="唯品会";
        } 
        
           
        $data=fetch_platform_data($platform_name,$product_id,$url);
        $result=[];
        

        dd($data);
    }

    //根据链接获取商品详情  
    public function fetch_url_goods_detail($request,$data,$is_zdm=false)
    {
        $result=$this->SmzdmLianJieJieXi($request,$data,$is_zdm);

        if($result['result']){
           $result= $result['result'][0];
           //dd($result);
        }else{
            $result=[];
        }
        if(!empty($result)){
            $platform=$result['platform'];
            $product_id=$result['product_id'];
           
        }

        if(!empty($product_id)){
            $hdata=[
                'product_id'=>$product_id,
                'platform_name'=>$platform
            ];
            $moneyRate=$this->getMoneyRate($request,$hdata);
           // dd($moneyRate);
            return $moneyRate;

        }

        return false;

    }
    

}
